package com.yellow.routingservice.service;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class GeocodingService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${amap.key}") // 从application.properties中读取高德地图API的Key
    private String amapKey;

    public Map<String, Double> getCoordinates(String address) throws JSONException {
        String url = "https://restapi.amap.com/v3/geocode/geo?address={address}&output=JSON&key={key}";

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("address", address);
        uriVariables.put("key", amapKey);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, uriVariables);
        String responseBody = responseEntity.getBody();

        Map<String, Double> coordinates = new HashMap<>();
        if (responseBody != null) {
            JSONObject jsonObject = new JSONObject(responseBody);
            String status = jsonObject.getString("status");
            if ("1".equals(status) && jsonObject.getJSONArray("geocodes").length() > 0) {
                String location = jsonObject.getJSONArray("geocodes").getJSONObject(0).getString("location");
                String[] parts = location.split(",");
                coordinates.put("longitude", Double.parseDouble(parts[0]));
                coordinates.put("latitude", Double.parseDouble(parts[1]));
            }
        }
        return coordinates;
    }
}